package cn.hl.pet.service.impl;

import cn.hl.pet.domain.PetType;
import cn.hl.pet.mapper.PetTypeMapper;
import cn.hl.pet.service.IPetTypeService;
import cn.hl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTypeTree() {
        Map<Long, PetType> map = new HashMap<>();
        List<PetType> types = petTypeMapper.findAll();
        for (PetType type: types) {
            map.put(type.getId(),type);
        }
        List<PetType> tree = new ArrayList<>();
        for (PetType type: types) {
            if (type.getPid() == null) {
                tree.add(type);
            } else {
                Long pid = type.getPid();
                PetType pType = map.get(pid);
                if (pType != null) {
                    pType.getChildren().add(type);
                }
            }
        }
        return tree;
    }
}
